/*
 * Description: install manager
 */

#include <thread>
#include <functional>
#include <memory>
#include "common/guest_utils.h"
#include "error.h"
#include "log.h"
#include "install_lifecycle_handler.h"
#include "dfx/model/app_using_data.h"
#include "performance/accelerator/installation_scene_accelerator.h"
using namespace COMMON;

namespace PERF {
void InstallLifeCycleHandler::Init()
{
    LOG_INFO("[INSTALL - START]::InstallLifeCycleHandler Init");
    APPWHITELIST.Init();
    INSTALLATIONSCENEACCLERATOR.Init();
}
void InstallLifeCycleHandler::Quit()
{
    LOG_INFO("[INSTALL - START]::InstallLifeCycleHandler Quit");
    INSTALLATIONSCENEACCLERATOR.Quit();
}
void InstallLifeCycleHandler::Start(std::shared_ptr<PerfInfo> perfInfo)
{
	//Received a message sent from filter agent. A process is created
    if (perfInfo == nullptr) {
        LOG_ERR("[INSTALL - Start] - perfInfo is null!");
        return;
    }
    if (perfInfo->scene == PERF::PERF_SCENE::APP_CREATE_FOLDER || perfInfo->scene == PERF_SCENE::APP_INSTALL) {
        std::thread tAppInstallCycle([this, perfInfo]() {
            INSTALLATIONSCENEACCLERATOR.OnBegin(perfInfo);
            });
        tAppInstallCycle.detach();
    }
}
void InstallLifeCycleHandler::Stop(std::shared_ptr<PerfInfo> perfInfo)
{
	//Received a message sent from filter agent. An installation is finished
    if (perfInfo == nullptr) {
        LOG_ERR("[INSTALL - Start] - perfInfo is null!");
        return;
    }
    LOG_INFO("[INSTALL - Stop] - start {}.", perfInfo->appName.c_str());
    if (perfInfo->processId == 0) {
        LOG_ERR("[PERF - OnEnd] - failed {} processID is 0.", perfInfo->appName.c_str());
        return;
    }
    INSTALLATIONSCENEACCLERATOR.OnEnd(perfInfo);
}

void InstallLifeCycleHandler::Start(const DFX::AppEventData perfEvent)
{
    //Received a message sent from filter agent. A process is created
    std::shared_ptr<PerfInfo> perfInfo = std::make_shared<PerfInfo>();
    perfInfo->appName = perfEvent.name;
    perfInfo->appPath = perfEvent.filePath;
    perfInfo->scene = PERF::PERF_SCENE::APP_INSTALL;
    perfInfo->sceneStr = PERF::appInstall;
    perfInfo->processId = perfEvent.pid;
    INSTALLATIONSCENEACCLERATOR.OnBegin(perfInfo);
}
void InstallLifeCycleHandler::Stop(const DFX::AppEventData perfEvent)
{
    //Received a message sent from filter agent. An installation is finished
    std::shared_ptr<PerfInfo> perfInfo = std::make_shared<PerfInfo>();
    perfInfo->appName = perfEvent.name;
    perfInfo->appPath = perfEvent.filePath;
    perfInfo->scene = PERF::PERF_SCENE::APP_INSTALL;
    perfInfo->sceneStr = PERF::appInstall;
    perfInfo->processId = perfEvent.pid;
    INSTALLATIONSCENEACCLERATOR.OnEnd(perfInfo);
}
}